package com.yequan.spring.bean.definition;

import com.yequan.spring.bean.factory.DefaultUserFactory;
import com.yequan.spring.bean.factory.UserFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * Bean初始化
 * 1.通过@PostConstruct注解
 * 2.实现InitializationBean接口的afterPropertiesSet方法
 * 3.自定义初始化方法
 *
 * @author : Administrator
 * @date : 2020/4/6
 */
@Configuration
public class BeanInitializationDemo {

    public static void main(String[] args) {
        //创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 注册 Configuration class 配置类
        applicationContext.register(BeanInitializationDemo.class);

        //启动 Spring 应用上下文
        applicationContext.refresh();

        System.out.println("Spring 应用上下文已启动...");

        UserFactory userFactory = applicationContext.getBean(UserFactory.class);
        System.out.println(userFactory);

        System.out.println("Spring 应用上下文准备关闭...");

        //关闭 Spring 应用上下文
        applicationContext.close();

        System.out.println("Spring 应用上下文已关闭...");

    }

    @Bean(initMethod = "initUserFactory",destroyMethod = "destroyCustom")
//    @Lazy//延迟初始化
    public UserFactory userFactory() {
        return new DefaultUserFactory();
    }

}
